package com.fancy.application.framework.dic.method;

import cn.hutool.core.util.ClassUtil;
import com.fancy.application.framework.dic.model.DictionaryObj;
import lombok.extern.log4j.Log4j2;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Log4j2
public class Dict {

//    private Dict(){}
    private final Map<String,DictionaryObj> map = new HashMap<>();

    public void load() {
        System.out.println("开始加载数据字典...");
        IAnnotationManager annotationManager = new AnnotationManager();
        Set<Class<?>> classSet = ClassUtil.scanPackage("com.fancy.application");
        classSet.forEach(aClass -> {
            DictionaryObj dictionaryObj =  annotationManager.getDicObj(aClass);
            if(dictionaryObj!=null){
                String modelName = aClass.getName();
                map.put(modelName,dictionaryObj);
                log.debug("字典{}加载成功...",modelName);
            }
        });
        System.out.println("加载数据字典结束...");
    }

    /**
     * 类级的内部类，也就是静态的成员式内部类，该内部类的实例与外部类的实例
     * 没有绑定关系，而且只有被调用到才会装载，从而实现了延迟加载
     */
    private static class DictHolder{
        /**
         * 静态初始化器，由JVM来保证线程安全
         */
        private static final Dict instance = new Dict();
    }
    public static  Dict getInstance(){
        return DictHolder.instance;
    }

    public Map<String,DictionaryObj> getDictMap(){
        return map;
    }

    public String getDicTableNameByModelName(String modelName){
        DictionaryObj dictionaryObj = this.getDictMap().get(modelName);
        return dictionaryObj.getTableName();
    }

}
